<template>
  <view class="container">
    <!-- 配送方式选择 -->
    <view class="delivery-type-section">
      <text class="section-title">配送方式</text>
      <view class="delivery-type-list">
        <view class="delivery-type-item" 
              :class="{ 
                active: deliveryType === 1, 
                disabled: merchant.supportDelivery === 1 && subtotal < merchant.minPrice 
              }" 
              @click="selectDeliveryType(1)" 
              v-if="merchant.supportDelivery === 1">
          <image class="type-icon" src="/static/icons/waimai.svg" mode="aspectFit"></image>
          <view class="type-info">
            <text class="type-name">外卖配送</text>
            <text class="type-desc" v-if="subtotal >= merchant.minPrice">约{{ merchant.deliveryTime || '30分钟' }}送达</text>
            <text class="type-desc shortage-tip" v-else>差¥{{ (merchant.minPrice - subtotal).toFixed(2) }}可配送</text>
          </view>
          <view class="radio-icon" v-if="deliveryType === 1">✓</view>
        </view>
        <view class="delivery-type-item" :class="{ active: deliveryType === 2 }" @click="selectDeliveryType(2)" v-if="merchant.supportDineIn === 1">
          <image class="type-icon" src="/static/icons/tangshi.svg" mode="aspectFit"></image>
          <view class="type-info">
            <text class="type-name">堂食就餐</text>
            <text class="type-desc">请到店就餐</text>
          </view>
          <view class="radio-icon" v-if="deliveryType === 2">✓</view>
        </view>
        <view class="delivery-type-item" :class="{ active: deliveryType === 3 }" @click="selectDeliveryType(3)" v-if="merchant.supportTakeout === 1">
          <image class="type-icon" src="/static/icons/ziqu.svg" mode="aspectFit"></image>
          <view class="type-info">
            <text class="type-name">到店自取</text>
            <text class="type-desc">约{{ merchant.baseTime }}分钟后可取</text>
          </view>
          <view class="radio-icon" v-if="deliveryType === 3">✓</view>
        </view>
      </view>
    </view>

    <!-- 配送地址 -->
    <view class="address-section" v-if="deliveryType === 1">
      <view class="address-info" @click="goToAddress">
        <view class="address-left">
          <text class="address-icon">📍</text>
        </view>
        <view class="address-content">
          <view class="address-header">
            <text class="address-name">{{ selectedAddress.name || '请选择收货地址' }}</text>
            <text class="address-phone" v-if="selectedAddress.phone">{{ selectedAddress.phone }}</text>
          </view>
          <text class="address-detail" v-if="selectedAddress.address">{{ selectedAddress.address }} {{
            selectedAddress.detail }}</text>
          <text class="address-detail no-address" v-else>点击选择收货地址</text>
        </view>
        <view class="address-right">
          <text class="arrow-icon">></text>
        </view>
      </view>
      <view class="delivery-time">
        <text class="time-label">送达时间</text>
        <view class="time-options">
          <text class="time-option" :class="{ active: deliveryTimeType === 1 }"
            @click="selectDeliveryTime(1)">尽快送达</text>
          <text class="time-option" :class="{ active: deliveryTimeType === 2 }"
            @click="selectDeliveryTime(2)">预约</text>
        </view>
        <picker v-if="deliveryTimeType === 2" mode="time" :value="scheduleTime" start="06:00" end="22:00"
          @change="onTimeChange">
          <view class="schedule-time">{{ scheduleTime }}</view>
        </picker>
      </view>
    </view>

    <!-- 商家和商品信息 -->
    <view class="merchant-section">
      <view class="merchant-info">
        <image class="merchant-logo" :src="merchant.logo || '/static/icons/default-merchant.png'" mode="aspectFill">
        </image>
        <text class="merchant-name">{{ merchant.name }}</text>
      </view>
      <view class="goods-list">
        <view class="goods-item" v-for="(item, index) in cartItems" :key="index">
          <view class="goods-info">
            <text class="goods-name">{{ item.name }}</text>
            <text class="goods-specs" v-if="item.specificationsStr">{{ item.specificationsStr }}</text>
          </view>
          <view class="goods-price-info">
            <text class="goods-quantity">x{{ item.quantity }}</text>
            <text class="goods-price">¥{{ ((item.price || 0) * item.quantity).toFixed(2) }}</text>
          </view>
        </view>
      </view>
      <view class="fee-item" v-if="deliveryType === 1">
        <text>配送费</text>
        <text class="fee-amount">¥{{ (merchant.deliveryFee || 0).toFixed(2) }}</text>
      </view>
      <view class="fee-item" v-if="totalPackagingFee > 0">
        <text>打包费</text>
        <text class="fee-amount">¥{{ totalPackagingFee.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 优惠券 -->
    <view class="coupon-section" @click="showCouponPopup">
      <text>优惠券</text>
      <view class="coupon-right inline">
        <view class="coupon-selected-info" v-if="selectedCoupon">
          <text class="coupon-name">{{ selectedCoupon.name }}</text>
          <text class="coupon-value">
            <span v-if="selectedCoupon.type === 1">-¥{{ (selectedCoupon.value || 0).toFixed(2) }}</span>
            <span v-else-if="selectedCoupon.type === 2">{{ (selectedCoupon.value * 10).toFixed(1) }}折</span>
          </text>
        </view>
        <text class="coupon-placeholder" v-else>{{ availableCoupons.length }}张可用</text>
        <text class="arrow-icon">></text>
      </view>
    </view>

    <!-- 备注 -->
    <view class="remark-section">
      <text>备注</text>
      <input class="remark-input" v-model="remark" placeholder="请输入备注信息" maxlength="50" />
    </view>

    <!-- 积分抵扣 -->
    <view class="points-section">
      <text>积分抵扣</text>
      <view class="points-info">
        <text>可用积分: {{ userInfo.points || 0 }}</text>
        <switch :checked="usePoints" @change="toggleUsePoints" color="#ff6b6b" />
      </view>
      <text class="points-tip" v-if="usePoints">已使用{{ pointsToUse }}积分，抵扣{{ pointsDiscount.toFixed(2) }}元</text>
    </view>

    <!-- 优惠限制提示 -->
    <view class="discount-limit-section" v-if="deliveryType === 1 && maxDiscountAmount > 0">
      <view class="limit-info">
        <text class="limit-title">💡 优惠限制提示</text>
        <text class="limit-desc">本单最多可优惠¥{{ maxDiscountAmount.toFixed(2) }}</text>
        <text class="limit-desc">当前已优惠¥{{ (getCurrentDiscountAmount() + (usePoints ? pointsDiscount : 0)).toFixed(2) }}</text>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-section">
      <text>支付方式</text>
      <view class="payment-methods">
        <view class="payment-method" v-for="method in paymentMethodsList" :key="method.id"
          :class="{ active: selectedPaymentMethod === method.id }" @click="selectPaymentMethod(method.id)">
          <image class="payment-icon" :src="method.icon" mode="aspectFit"></image>
          <text>{{ method.name }}</text>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="footer">
      <view class="price-info">
        <text class="total-label">合计</text>
        <text class="actual-pay">¥{{ actualPay.toFixed(2) }}</text>
      </view>
      <button class="submit-btn" @click="submitOrder">提交订单</button>
    </view>

    <!-- 优惠券弹窗 -->
    <uni-popup ref="couponPopupRef" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text>选择优惠券</text>
          <text @click="closeCouponPopup">✕</text>
        </view>
        <view class="coupon-list">
          <view class="coupon-item" v-for="coupon in availableCoupons" :key="coupon.id" @click="selectCoupon(coupon)">
            <view class="coupon-left">
              <text class="coupon-amount" v-if="coupon.type === 1">¥{{ coupon.value }}</text>
              <text class="coupon-amount" v-else-if="coupon.type === 2">{{ (coupon.value * 10).toFixed(1) }}折</text>
              <text class="coupon-condition">满{{ coupon.minConsume }}可用</text>
            </view>
            <view class="coupon-right">
              <text class="coupon-name">{{ coupon.name }}</text>
              <text class="coupon-time">有效期至{{ coupon.useEndTime }}</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 遮罩层获取手机号 -->
    <uni-popup ref="phoneMaskRef" type="center" :mask-click="false">
      <view class="phone-mask-content">
        <text class="phone-mask-title">授权获取手机号</text>
        <text class="phone-mask-desc">为确保订单顺利送达，请授权获取您的微信手机号</text>
        <button class="phone-mask-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">微信一键授权</button>
        <button class="phone-mask-cancel" @click="closePhoneMask">暂不授权</button>
      </view>
    </uni-popup>

  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useCartStore } from '@/store/cart.js'
import { useUserStore } from '@/store/user.js'
import { getCouponList } from '@/api/coupon.js'
import { getCurrentLocation } from '@/utils/location.js';
import {getMerchantById} from "@/api/merchant.js";
import estimateTime from '@/utils/time.js';
import {getUserAddressList} from "@/api/address.js";
import { submitOrder as submitUserOrder, createWechatPayOrder } from "@/api/order.js";
import { getWechatPhoneNumber } from '@/api/wechat'
import { getUserInfo } from '@/api/user.js'
import config from '@/config.js'

// 响应式状态
const merchantId = ref(0)
const merchant = ref({})
const cartItems = ref([])
const selectedAddress = ref({})
const deliveryTimeType = ref(1) // 1-尽快送达，2-预约
const scheduleTime = ref('12:00')
const availableCoupons = ref([])
const selectedCoupon = ref(null)
const remark = ref('')
const paymentMethodsList = ref([
  {
    id: 1,
    name: '微信支付',
    icon: '/static/icons/wechat-pay.svg',
    description: '微信支付'
  }
])
const selectedPaymentMethod = ref(1)
const userInfo = ref({})
const usePoints = ref(false)
const pointsToUse = ref(0)
const pointsDiscount = ref(0)
const deliveryType = ref(1) // 默认外卖配送
const couponPopupRef = ref(null)
const phoneMaskRef = ref(null)
const showPhoneMask = ref(false)

const openPhoneMask = () => {
  showPhoneMask.value = true
  phoneMaskRef.value && phoneMaskRef.value.open()
}
const closePhoneMask = () => {
  showPhoneMask.value = false
  phoneMaskRef.value && phoneMaskRef.value.close()
}

// 公共手机号输入弹窗方法
const showPhoneInputModal = async () => {
  return new Promise((resolve) => {
    uni.showModal({
      title: '请输入手机号',
      content: '',
      editable: true,
      placeholderText: '请输入11位手机号',
      confirmText: '确认',
      cancelText: '取消',
      success: async (inputRes) => {
        if (inputRes.confirm && /^1[3-9]\d{9}$/.test(inputRes.content)) {
          userInfo.value.phone = inputRes.content;
          const userStore = useUserStore();
          await userStore.updateUserInfo(userInfo.value);
          closePhoneMask();
          resolve(true);
        } else if (inputRes.confirm) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          });
          resolve(false);
        } else {
          closePhoneMask();
          resolve(false);
        }
      }
    });
  });
}

const onGetPhoneNumber = async (e) => {
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    const code = e.detail.code
    try {
      const decryptRes = await getWechatPhoneNumber(code);
      if (!decryptRes.data) {
        // 解密失败，兜底弹窗输入手机号
        const ok = await showPhoneInputModal();
        if (ok) {
          // 自动继续提交订单
          submitOrder();
        }
        return;
      }
      userInfo.value.phone = decryptRes.data
      const userStore = useUserStore()
      await userStore.updateUserInfo(userInfo.value)
      closePhoneMask()
      // 自动继续提交订单
      submitOrder()
    } catch (err) {
      // 微信接口失败，兜底弹窗输入手机号
      const ok = await showPhoneInputModal();
      if (ok) {
        submitOrder();
      }
      return;
    }
  } else {
    // 用户未授权，兜底弹窗输入手机号
    const ok = await showPhoneInputModal();
    if (ok) {
      submitOrder();
    }
    return;
  }
}


// 计算属性
/**
 * 计算商品小计原价
 */
const subOriginal = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + (item.originalPrice || item.price) * item.quantity, 0)
})
/**
 * 计算商品小计金额
 */
 const subtotal = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

/**
 * 计算总打包费
 */
const totalPackagingFee = computed(() => {
  if (deliveryType.value === 2) return 0 // 堂食就餐不需要打包费
  return cartItems.value.reduce((sum, item) => sum + (item.packagingFee || 0) * item.quantity, 0)
})

/**
 * 计算最低实付金额（基于微信分账规则）
 */
const minActualPay = computed(() => {
  const userStore = useUserStore()
  const deliveryFeeRatio = userStore.deliveryFeeRatio || 0
  const deliveryFee = deliveryType.value === 1 ? (merchant.value?.deliveryFee || 0) : 0
  // 最低实付金额 = 配送费 / 比率
  return deliveryFee > 0 ? deliveryFee / deliveryFeeRatio : 0
})

/**
 * 计算可优惠的金额
 */
const maxDiscountAmount = computed(() => {
  let total = subtotal.value + totalPackagingFee.value
  // 只有外卖配送才加配送费
  if (deliveryType.value === 1) {
    total += (merchant.value?.deliveryFee || 0)
  }
  // 可优惠金额 = 订单总金额 - 最低实付金额
  return Math.max(total - minActualPay.value, 0)
})

/**
 * 计算订单实付金额
 */
const actualPay = computed(() => {
  let total = subtotal.value + totalPackagingFee.value
  // 只有外卖配送才加配送费
  if (deliveryType.value === 1) {
    total += (merchant.value?.deliveryFee || 0)
  }
  if (selectedCoupon.value) {
    // 使用实际优惠金额，如果没有则根据类型计算
    let couponDiscount = selectedCoupon.value.actualDiscountAmount
    if (!couponDiscount) {
      if (selectedCoupon.value.type === 1) {
        couponDiscount = selectedCoupon.value.value
      } else if (selectedCoupon.value.type === 2) {
        couponDiscount = subtotal.value * (1 - selectedCoupon.value.value)
      }
    }
    total -= couponDiscount
  }
  if (usePoints.value && pointsDiscount.value > 0) {
    total -= pointsDiscount.value
  }
  return Math.max(total, 0)
})

/**
 * 初始化数据
 */
const initData = async () => {
  const cartStore = useCartStore()
  cartItems.value = cartStore.items
  
  try {
    //获取当前选择的位置
  const location = await getCurrentLocation();
    const res = await getMerchantById(merchantId.value, location.latitude, location.longitude)
    merchant.value = res.data
    merchant.value.deliveryTime = estimateTime(merchant.value.baseTime, merchant.value.distance)
    
    // 检查默认的外卖配送是否满足起送价，如果不满足则自动切换到其他配送方式
    if (deliveryType.value === 1 && subtotal.value < merchant.value.minPrice) {
      // 优先选择堂食就餐，其次选择到店自取
      if (merchant.value.supportDineIn === 1) {
        deliveryType.value = 2;
      } else if (merchant.value.supportTakeout === 1) {
        deliveryType.value = 3;
      }
      // 如果都不支持，保持外卖配送但会显示差额提示
    }
  } catch (error) {
    console.error('获取商户信息失败:', error)
  }

  // 获取可用优惠券
  try {
    const res = await getCouponList({ 
      status: 1,
      minConsume: subtotal.value
    })
    availableCoupons.value = res.data
  } catch (error) {
    console.error('获取优惠券失败:', error)
    availableCoupons.value = []
  }

  // 获取默认地址
  let addressList = []
  try {
    const res = await getUserAddressList()
    addressList = res.data || []
    selectedAddress.value = addressList.find(addr => addr.isDefault) || addressList[0] || {}
  } catch (error) {
    console.error('获取用户收货地址失败:', error)
    selectedAddress.value = {}
  }

  
  // 获取用户信息
  const userStore = useUserStore()
  try {
    const res = await getUserInfo()
    userInfo.value = res.data || { points: 0 }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = userStore.userInfo || { points: 0 }
  }

  // 计算可用积分和抵扣金额
  calculatePointsDiscount()
}

/**
 * 跳转到地址列表页
 */
const goToAddress = () => {
  uni.navigateTo({
    url: '/pages/address/select'
  })
}

/**
 * 选择配送方式
 * @param {number} type - 配送类型：1-外卖配送，2-堂食就餐，3-到店自取
 */
const selectDeliveryType = (type) => {
  if (deliveryType.value === type) return;

  // 如果选择外卖配送，检查是否满足起送价
  if (type === 1 && subtotal.value < merchant.value.minPrice) {
    uni.showToast({
      title: `差¥${(merchant.value.minPrice - subtotal.value).toFixed(2)}可配送`,
      icon: 'none',
      duration: 2000
    });
    return;
  }

  deliveryType.value = type;

  // 显示切换提示
  uni.showToast({
    title: type === 1 ? '已切换为外卖配送' :
      type === 2 ? '已切换为堂食就餐' : '已切换为到店自取',
    icon: 'none',
    duration: 1500
  });

  // 如果是外卖配送，需要选择地址
  if (type === 1 && !selectedAddress.value.id) {
    setTimeout(() => {
      uni.showToast({
        title: '请选择配送地址',
        icon: 'none'
      });
    }, 1500);
  }
}

/**
 * 选择配送时间类型
 * @param {string} type - 时间类型
 */
const selectDeliveryTime = (type) => {
  deliveryTimeType.value = type
}

/**
 * 时间选择器变化处理
 * @param {Object} e - 事件对象
 */
const onTimeChange = (e) => {
  scheduleTime.value = e.detail.value
}

/**
 * 显示优惠券弹窗
 */
const showCouponPopup = () => {
  if (couponPopupRef.value) {
    couponPopupRef.value.open()
  }
}

/**
 * 关闭优惠券弹窗
 */
const closeCouponPopup = () => {
  if (couponPopupRef.value) {
    couponPopupRef.value.close()
  }
}

/**
 * 选择优惠券
 * @param {Object} coupon - 优惠券对象
 */
const selectCoupon = (coupon) => {
  // 计算优惠券实际优惠金额
  let couponDiscountAmount = 0
  if (coupon.type === 1) {
    // 满减券：直接使用面值
    couponDiscountAmount = coupon.value
  } else if (coupon.type === 2) {
    // 折扣券：根据折扣值和商品小计计算优惠金额
    couponDiscountAmount = subtotal.value * (1 - coupon.value)
  }
  
  // 验证选择该优惠券后是否超出优惠限制
  const totalDiscount = couponDiscountAmount + (usePoints.value ? pointsDiscount.value : 0)
  if (totalDiscount > maxDiscountAmount.value) {
    uni.showToast({
      title: `优惠券和积分抵扣累计不能超过¥${maxDiscountAmount.value.toFixed(2)}`,
      icon: 'none',
      duration: 3000
    })
    return
  }
  
  // 为优惠券对象添加计算后的实际优惠金额
  coupon.actualDiscountAmount = couponDiscountAmount
  selectedCoupon.value = coupon
  
  // 重新计算积分抵扣，确保不超出限制
  if (usePoints.value) {
    calculatePointsDiscount()
  }
  closeCouponPopup()
}

/**
 * 切换是否使用积分
 * @param {Object} e - 事件对象
 */
const toggleUsePoints = (e) => {
  usePoints.value = e.detail.value
  calculatePointsDiscount()
}

/**
 * 获取当前优惠券的实际优惠金额
 */
const getCurrentDiscountAmount = () => {
  if (!selectedCoupon.value) return 0
  
  // 如果已经计算过实际优惠金额，直接返回
  if (selectedCoupon.value.actualDiscountAmount) {
    return selectedCoupon.value.actualDiscountAmount
  }
  
  // 根据优惠券类型计算优惠金额
  if (selectedCoupon.value.type === 1) {
    // 满减券：直接使用面值
    return selectedCoupon.value.value
  } else if (selectedCoupon.value.type === 2) {
    // 折扣券：根据折扣值和商品小计计算优惠金额
    return subtotal.value * (1 - selectedCoupon.value.value)
  }
  
  return 0
}

/**
 * 计算积分抵扣金额
 */
const calculatePointsDiscount = () => {
  if (usePoints.value && userInfo.value.points > 0) {
    // 计算能使用的最大积分（基于商品金额）
    let maxPointsByAmount = Math.min(userInfo.value.points, subtotal.value * 100)
    
    // 计算基于优惠限制的最大积分
    const couponDiscount = getCurrentDiscountAmount()
    const remainingDiscountAmount = Math.max(maxDiscountAmount.value - couponDiscount, 0)
    const maxPointsByLimit = Math.floor(remainingDiscountAmount * 100) // 转换为积分
    
    // 取两者中的较小值
    const finalMaxPoints = Math.min(maxPointsByAmount, maxPointsByLimit)
    
    pointsToUse.value = finalMaxPoints
    // 积分抵扣金额（1积分=0.01元）
    pointsDiscount.value = finalMaxPoints * 0.01
  } else {
    pointsToUse.value = 0
    pointsDiscount.value = 0
  }
}

/**
 * 选择支付方式
 * @param {number} methodId - 支付方式ID
 */
const selectPaymentMethod = (methodId) => {
  selectedPaymentMethod.value = methodId
}

const submitOrder = async () => {
  // 验证必填信息
  if (deliveryType.value === 1 && !selectedAddress.value.id) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }
  // 检查用户手机号
  if (!userInfo.value.phone) {
    openPhoneMask()
    return
  }
  
  // 验证优惠限制
  const totalDiscount = getCurrentDiscountAmount() + (usePoints.value ? pointsDiscount.value : 0)
  if (totalDiscount > maxDiscountAmount.value) {
    uni.showToast({
      title: `优惠券和积分抵扣累计不能超过¥${maxDiscountAmount.value.toFixed(2)}`,
      icon: 'none',
      duration: 3000
    })
    return
  }
  
  // 验证实付金额不能低于最低要求
  if (actualPay.value < minActualPay.value) {
    uni.showToast({
      title: `实付金额不能低于¥${minActualPay.value.toFixed(2)}`,
      icon: 'none',
      duration: 3000
    })
    return
  }

  // 请求订阅消息授权
  try {
    uni.requestSubscribeMessage({
      tmplIds: [
        config.wechat.subscribeTemplates.orderCancel, // 订单取消通知模板ID
        config.wechat.subscribeTemplates.orderComplete // 订单完成通知模板ID
      ],
      success: (res) => {
        console.log('订阅消息授权结果:', res)
        // 无论用户是否同意订阅，都继续提交订单
        proceedWithOrder()
      },
      fail: (err) => {
        console.log('订阅消息授权失败:', err)
        // 授权失败也继续提交订单
        proceedWithOrder()
      }
    })
  } catch (error) {
    console.log('订阅消息授权异常:', error)
    // 授权异常也继续提交订单
    proceedWithOrder()
  }
  
  return // 等待授权结果后再继续
}

// 继续提交订单的逻辑
const proceedWithOrder = async () => {
  // 构建订单数据
  const orderData = {
    merchantId: merchantId.value,
    merchantName: merchant.value.name,
    merchantLogo: merchant.value.logo,
    goods: cartItems.value,
    deliveryType: deliveryType.value,
    receiverName: selectedAddress.value.name,
    receiverPhone: selectedAddress.value.phone,
    deliveryAddress: deliveryType.value === 1 ?
      `${selectedAddress.value.address} ${selectedAddress.value.detail}` : '',
    originalPrice: subOriginal.value,
    totalPrice: subtotal.value,
    deliveryFee: deliveryType.value === 1 ? merchant.value.deliveryFee : 0,
    discount: getCurrentDiscountAmount() + pointsDiscount.value,
    actualPay: actualPay.value,
    paymentMethodId: selectedPaymentMethod.value,
    remark: remark.value,
    ...(selectedCoupon.value ? { userCouponId: selectedCoupon.value.id } : {}),
    pointsUsed: usePoints.value? pointsToUse.value : 0,
    pointsDiscount: usePoints.value? pointsDiscount.value : 0,
    totalPackagingFee: totalPackagingFee.value,
    // 其他订单信息...
  }

  // 如果是外卖配送，则添加配送时间信息
  if (orderData.deliveryType === 1) {
    orderData.deliveryTimeType = deliveryTimeType.value
    if (deliveryTimeType.value === 2) { // 2-预约
      orderData.scheduleTime = scheduleTime.value
    }
  }

  console.log('提交订单', JSON.stringify(orderData))

  // 调用真实接口提交订单
  uni.showLoading({
    title: '正在提交...'
  })

  try {
    const res = await submitUserOrder(orderData)
    
    const orderId = res.data
    
    // 如果选择微信支付，则调用微信支付接口
    if (selectedPaymentMethod.value === 1) { // 假设1是微信支付
      try {
        // 调用创建微信支付订单接口
        const payRes = await createWechatPayOrder(orderId)
        
        const payData = payRes.data
          
          // 调用微信支付
          uni.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.packageVal,
            signType: payData.signType,
            paySign: payData.paySign,
            success: (payResult) => {
               console.log('支付成功:', payResult)
               uni.hideLoading()
               
               // 积分已在后端扣减，无需更新本地缓存
               // 清空购物车
               const cartStore = useCartStore()
               cartStore.clearCart()
               
               // 跳转到订单成功页
               uni.redirectTo({
                 url: `/pages/order/success?id=${orderId}`
               })
             },
             fail: (payError) => {
               console.error('支付失败:', payError)
               uni.hideLoading()
               uni.showToast({
                 title: '支付失败，请重试',
                 icon: 'none'
               })
               // 支付失败，跳转到订单详情页
               uni.redirectTo({
                 url: `/pages/order/detail?id=${orderId}`
               })
             }
          })
      } catch (payError) {
         console.error('创建支付订单失败:', payError)
         uni.hideLoading()
         uni.showToast({
           title: '创建支付订单失败: ' + (payError.message || '未知错误'),
           icon: 'none'
         })
         // 创建支付订单失败，跳转到订单详情页
         uni.redirectTo({
           url: `/pages/order/detail?id=${orderId}`
         })
       }
    } else {
       // 非微信支付，直接跳转到订单成功页
       // 积分已在后端扣减，无需更新本地缓存
       // 清空购物车
       const cartStore = useCartStore()
       await cartStore.clearCart()
       
       uni.hideLoading()
       
       // 跳转到订单成功页
       uni.redirectTo({
         url: `/pages/order/success?id=${orderId}`
    })
  }
 } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '订单提交失败: ' + (error.message || '未知错误'),
      icon: 'none'
    })
    console.error('订单提交失败:', error)
  }
}


// 页面加载钩子
onLoad((options) => {
  console.log("onLoad options===", options)
  merchantId.value = parseInt(options?.merchantId) || 0
  // 添加地址选择事件监听
  uni.$on('addressSelected', (address) => {
    console.log("addressSelected", address)
    selectedAddress.value = address
  })
  initData()
})
// 页面卸载时移除监听
onUnload(() => {
  uni.$off('addressSelected')
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  padding-bottom: 120rpx;
  background: #f0f2f5;
}

/* 配送方式选择 */
.delivery-type-section {
  background: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
    display: block;
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 32rpx;
      background: linear-gradient(to bottom, #ff9a9e, #ff6b6b);
      border-radius: 6rpx;
    }
  }

  .delivery-type-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .delivery-type-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    background-color: #f8f8f8;
    border-radius: 16rpx;
    position: relative;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &.active {
      background-color: #fff1f0;
      border: 2rpx solid #ff6b6b;
      box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.1);
    }

    &.disabled {
      background-color: #f5f5f5;
      opacity: 0.6;
      cursor: not-allowed;
      
      .type-icon {
        opacity: 0.5;
      }
      
      .type-name {
        color: #999;
      }
    }

    .type-icon {
      width: 56rpx;
      height: 56rpx;
      margin-right: 24rpx;
    }

    .type-info {
      flex: 1;
    }

    .type-name {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 8rpx;
      color: #333;
    }

    .type-desc {
      font-size: 24rpx;
      color: #666;
      
      &.shortage-tip {
        color: #ff9500;
        font-weight: bold;
        background: rgba(255, 149, 0, 0.1);
        padding: 4rpx 8rpx;
        border-radius: 8rpx;
        border: 1rpx solid rgba(255, 149, 0, 0.3);
        display: inline-block;
      }
    }

    .radio-icon {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #ff9a9e, #ff6b6b);
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
      box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.2);
    }
  }
}

/* 配送地址 */
.address-section {
  margin: 20rpx;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

/* 优惠限制提示 */
.discount-limit-section {
  margin: 20rpx;
  padding: 24rpx;
  background: linear-gradient(135deg, #fff9e6, #fff3cd);
  border-radius: 16rpx;
  border-left: 6rpx solid #ffc107;
  box-shadow: 0 2rpx 12rpx rgba(255, 193, 7, 0.1);
}

.limit-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.limit-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #856404;
  margin-bottom: 8rpx;
}

.limit-desc {
  font-size: 24rpx;
  color: #856404;
  line-height: 1.4;
}

.address-info {
  display: flex;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
}

.address-left {
  margin-right: 20rpx;
}

.address-icon {
  font-size: 40rpx;
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  -webkit-background-clip: text;
  color: transparent;
}

.address-content {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.address-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.address-phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;

  &.no-address {
    color: #ff6b6b;
    font-size: 26rpx;
  }
}

.address-right {
  padding: 20rpx;
}

.arrow-icon {
  color: #999;
  font-size: 24rpx;
}

.delivery-time {
  padding-top: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.time-label {
  font-size: 28rpx;
  color: #333;
}

.time-options {
  display: flex;
  gap: 20rpx;
}

.time-option {
  padding: 10rpx 24rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #666;
  background: #f7f8fa;
  transition: all 0.3s;
}

.time-option.active {
  background: linear-gradient(135deg, #ff9a9e, #ff6b6b);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
}

.schedule-time {
  font-size: 26rpx;
  color: #ff6b6b;
  padding: 10rpx 24rpx;
  background: #fff1f0;
  border-radius: 30rpx;
  border: 1rpx solid #ffccc7;
}

/* 商家和商品信息 */
.merchant-section {
  margin: 20rpx;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.merchant-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
}

.merchant-logo {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.merchant-name {
  font-size: 30rpx;
  font-weight: bold;
  background: linear-gradient(135deg, #333, #666);
  -webkit-background-clip: text;
  color: transparent;
}

.goods-list {
  padding: 20rpx 0;
}

.goods-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.goods-specs {
  font-size: 24rpx;
  color: #999;
}

.goods-price-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.goods-quantity {
  font-size: 26rpx;
  color: #666;
}

.goods-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 2rpx solid rgba(0, 0, 0, 0.05);
  font-size: 28rpx;
  color: #333;
  .fee-amount {
    color: #ff6b6b;
  }
}

/* 优惠券区域 */
.coupon-section {
  margin: 20rpx;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-section text {
  font-size: 28rpx;
  color: #333;
}

.coupon-right {
  display: flex;
  align-items: center;
  gap: 6rpx;
  white-space: nowrap;
  flex: 1;
  justify-content: flex-end;
  padding-left: 20rpx;
}

.coupon-selected-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4rpx;
}

.coupon-name {
  font-size: 24rpx;
  color: #666;
  max-width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.coupon-value {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 26rpx;
}

.coupon-placeholder {
  color: #666;
}

/* 备注区域 */
.remark-section {
  margin: 20rpx;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.remark-section text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}

.remark-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #333;
  background: #f7f8fa;
  border-radius: 12rpx;
  border: 1rpx solid #f0f0f0;
}

/* 积分抵扣 */
.points-section {
  margin: 20rpx;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.points-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.points-tip {
  font-size: 24rpx;
  color: #ff6b6b;
  margin-top: 10rpx;
}

/* 支付方式 */
.payment-section {
  margin: 20rpx;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.payment-section>text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.payment-methods {
  display: flex;
  gap: 20rpx;
}

.payment-method {
  width: 240rpx;
  padding: 20rpx;
  background: #f7f8fa;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
  transition: all 0.3s;
  border: 1rpx solid #f0f0f0;
}

.payment-method.active {
  background: #fff1f0;
  border: 2rpx solid #ff6b6b;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.1);
}

.payment-icon {
  width: 40rpx;
  height: 40rpx;
}

.payment-method text {
  font-size: 26rpx;
  color: #333;
}

/* 底部结算栏 */
.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  padding: 0 30rpx;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.price-info {
  display: flex;
  align-items: baseline;
  gap: 10rpx;
}

.total-label {
  font-size: 28rpx;
  color: #666;
}

.actual-pay {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.submit-btn {
  width: 240rpx;
  height: 72rpx;
  background: linear-gradient(135deg, #ff9a9e, #ff6b6b);
  border-radius: 36rpx;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
  transition: all 0.3s;
}

.submit-btn:active {
  transform: scale(0.95);
}

/* 优惠券弹窗 */
.popup-content {
  background: #ffffff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 30rpx;
  max-height: 70vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-header text {
  font-size: 32rpx;
  color: #333;
}

.popup-header text:last-child {
  color: #999;
  padding: 10rpx;
}

.coupon-list {
  max-height: calc(70vh - 100rpx);
  overflow-y: auto;
}

.coupon-item {
  display: flex;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #fff1f0;
  border-radius: 16rpx;
  position: relative;
  overflow: hidden;
  border: 1rpx solid #ffccc7;
}

.coupon-item::before {
  content: '';
  position: absolute;
  left: -10rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 20rpx;
  height: 20rpx;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 -120rpx 0 #fff, 0 120rpx 0 #fff;
}

.coupon-item::after {
  content: '';
  position: absolute;
  right: -10rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 20rpx;
  height: 20rpx;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 -120rpx 0 #fff, 0 120rpx 0 #fff;
}

.coupon-left {
  padding: 20rpx 40rpx;
  border-right: 2rpx dashed rgba(255, 107, 107, 0.3);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.coupon-amount {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 10rpx;
}

.coupon-condition {
  font-size: 24rpx;
  color: #666;
}

.coupon-right {
  flex: 1;
  padding: 20rpx 40rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.coupon-right.inline {
  flex-direction: row;
  /* 覆盖原有的 column */
  align-items: right;
  /* 如果需要垂直居右 */
}

.coupon-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.coupon-time {
  font-size: 24rpx;
  color: #999;
}

/* 遮罩层手机号弹窗美化 */
.phone-mask-content {
  background: #fff;
  border-radius: 24rpx;
  padding: 60rpx 40rpx 40rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
  min-width: 520rpx;
}
.phone-mask-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 24rpx;
  text-align: center;
}
.phone-mask-desc {
  font-size: 28rpx;
  color: #888;
  margin-bottom: 48rpx;
  text-align: center;
}
.phone-mask-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(90deg, #ff9a9e 0%, #ff6b6b 100%);
  color: #fff;
  font-size: 30rpx;
  font-weight: bold;
  border: none;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(255,107,107,0.15);
  transition: background 0.3s;
}
.phone-mask-btn:active {
  background: linear-gradient(90deg, #ff6b6b 0%, #ff9a9e 100%);
}
.phone-mask-cancel {
  width: 100%;
  height: 80rpx;
  background: #f7f8fa;
  color: #ff6b6b;
  font-size: 28rpx;
  border: none;
  border-radius: 16rpx;
  margin-top: 0;
  box-shadow: none;
}
</style>
